package com.example.myblog01.service.impl;

import com.example.myblog01.dao.BlogServiceDao;
import com.example.myblog01.dao.TypeServiceDao;
import com.example.myblog01.pojo.Type;
import com.example.myblog01.service.TypeService;
import javassist.NotFoundException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Transient;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TypeServiceimpl implements TypeService {

    @Autowired
    private TypeServiceDao typeServiceDao;

    private BlogServiceDao blogServiceDao;

    //    @Transient放在事务里面
    @Transient
    @Override
    public Type sevetype(Type type) {

        return typeServiceDao.save(type);
    }

    @Transient
    @Override
    public Type getType(Long id) {
        return typeServiceDao.getById(id);
    }

    @Transient
    @Override
    public Page<Type> ListType(Pageable pageable) {
        return typeServiceDao.findAll(pageable);
    }

    @Transient
    @Override
    public Type updateType(Long id, Type type) {
        Type t = typeServiceDao.findById(id).orElse(null);
        if (t == null) {
            try {
                throw new NotFoundException("不存在");
            } catch (NotFoundException e) {
                e.printStackTrace();
            }
        }
//        否则更新数据库
        BeanUtils.copyProperties(type,t);
        return typeServiceDao.save(t);
    }

    @Transient
    @Override
    public Type getTypeByName(String name) {
        return typeServiceDao.findByName(name);
    }

    @Transient
    @Override
    public void deletetype(Long id) {
        typeServiceDao.deleteById(id);
    }


    @Override
    public List<Type> listType() {
        return typeServiceDao.findAll();
    }


    @Override
    public List<Type> listTpyeTop(Integer size) {

//排序 按照blogs.size 从大到小
//        Sort.by(Sort.Direction.DESC, "blogs.size");
//        分页
//        Pageable pageable = new PageRequest(0,size,Sort.by(Sort.Direction.DESC, "blogs.size"));
        return typeServiceDao.findTop(PageRequest.of(0,size,Sort.by(Sort.Direction.DESC, "blogs.size")));
    }
}
